#include "raft_core/RaftCoreGrpc.h"

#include <grpcpp/server_builder.h>

#include <string>
#include <utility>

#include "raft_core/RaftCore.h"
#include "raft_core/rpc_proto/raft_rpc.grpc.pb.h"
#include "raft_utils/Config.h"

void raft::core::RaftCoreGrpc::start(std::shared_ptr<state_machine::StateMachine> state_machine,
                                     std::shared_ptr<utils::Command> command) {
    RaftCore service(std::move(state_machine), std::move(command));

    grpc::EnableDefaultHealthCheckService(true);

    auto server_address = "0.0.0.0:" +
                          std::to_string(utils::Config::getInstance()->get_raft_core_port());

    grpc::ServerBuilder builder;
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());

    builder.RegisterService(static_cast<raft_rpc_protoc::RaftRPC::Service *>(&service));
    builder.RegisterService(static_cast<middleware_rpc_proto::MiddlewareService::Service *>(&service));

    server_ = builder.BuildAndStart();

    log.info("[func-raft::core::RaftCoreGrpc::start] raft core grpc start on port: {}",
             utils::Config::getInstance()->get_raft_core_port());
    server_->Wait();
}

void raft::core::RaftCoreGrpc::stop() {
    if (server_) {
        server_->Shutdown();
        log.info("[func-raft::core::RaftCoreGrpc::stop()] raft core grpc stop now");
    }
}